<!-- eslint-disable max-len -->
<template>
  <div class="h100">
    <div class="h100" v-if="changeCompt=='ApplicationDetailSoftwareMC'">
        <!-- 各业务类型所对应的页面 -->
        <ApplicationDetailSoftwareMC 
        ref="actionCompt"
        :addInfoBtn="addInfoBtn"
        :showInfo="showInfo"
        
        :BottomType="BottomType" 
        @handleUrge="handleUrge"
        @handleCancel="handleCancel"
        @pass="pass"
        @reject="reject"
        @addReviewInfo="addReviewInfo"
        @addInfodrawBtn="addInfodrawBtn"
        @transferReviewInfo="transferReviewInfo"
        ></ApplicationDetailSoftwareMC>
    </div>
    <div class="h100" v-if="changeCompt=='ApplicationDetailRegisterCompt'">
        <!-- 用户注册申请的页面 -->
        <ApplicationDetailRegisterCompt 
          ref="actionCompt"
          :BottomType="BottomType" 
          @hancleStatusCheck="hancleStatusCheck"
          @handleUrge="handleUrge"
          @handleCancel="handleCancel"
          @pass="pass"
          @reject="reject"
          @transferReviewInfo="transferReviewInfo"
        ></ApplicationDetailRegisterCompt>
    </div>
    <div class="taskVerifyDetail h100" v-if="changeCompt!=='ApplicationDetailSoftwareMC' && changeCompt!=='ApplicationDetailRegisterCompt' && changeCompt!==''">
      <!-- 上方信息页面 -->
      <div class="taskVerifyDetailTop">
        <!-- 各业务类型所对应的页面 -->
        <component :is="changeCompt" @sendTaskType="getTaskType" @sendUploadType="getUploadType"></component>
        <!-- 审核流程 -->
        <review-process
          v-if="BottomType!==''"
          :isPendingReview="BottomType"
          @transTime="handleEndTime"
          @transFileLimit="handleFileLimit"
          @showInfo="handlerShowInfoBtn"
          @hideAddInfoBtn="handleAddInfodrawBtn"
          @addInfoBtn="addInfodrawBtn"
          @hideWithdrawBtn="handleHideWithdrawBtn"
          @checkStatus="hancleStatusCheck"/>
        <!-- 审核意见 -->
        <review-process-action
          ref="actionCompt"
          v-if="BottomType==='pendingReview'"
          :fileLimitObj="fileLimitObj"
        >
        </review-process-action>
      </div>
      <!-- 下方操作或审核结果反显 -->
      <div class="taskVerifyDetailFooter">
        <a-row>
          <a-col :md="2" :sm="2"></a-col>
          <a-col :md="18" :sm="18">
            <div v-if="BottomType==='pendingApplication'">
              <auth-button :auth="todoPerms.apply.urge" style="margin-right: 24px" @click="handleUrge" >
                {{ $t('urge') }}
              </auth-button >
              <auth-button :auth="todoPerms.apply.withdraw" v-if="!hideWithdrawBtn" @click="handleCancel"  style="margin-right: 24px" >
                {{ $t('withdraw') }}
              </auth-button >
            </div>
            <div v-if="BottomType==='passedApplication'">
              <span class="marginRightText ">{{ $t('auditResult') }}</span>
              <span class="marginRightTextBigger ok titleBold">{{ $t('passed') }}</span>
              <span class="marginRightText ">{{ $t('completeTime') }}</span><span class="marginRightText titleBold">{{ endTime }}</span>
              <span class="marginRightTextBigger ok titleBold " v-if="$route.query.swcode=='task_audit' && taskType==1"><a-button type="primary" @click="auditDetailView">{{ $t('auditDetailView') }}</a-button></span>
            </div>
            <div v-if="BottomType==='rejectedApplication'">
              <span class="marginRightText ">{{ $t('auditResult') }}</span>
              <span class="marginRightTextBigger reject titleBold">{{ $t('rejected') }}</span>
              <span class="marginRightText ">{{ $t('completeTime') }}</span><span class="titleBold">{{ endTime }}</span>
            </div>
            <div v-if="BottomType==='canceledApplication'">
              <span class="marginRightTextBigger titleBold">{{ $t('sqych') }}</span>
              <span class="marginRightText ">{{ $t('timeofCancel') }}</span>
              <span class="titleBold">{{ endTime }}</span>
            </div>
            <div v-if="BottomType==='pendingReview'">
              <auth-button :auth="todoPerms.review.pass" type="primary" style="margin-right: 24px;background:#ddd;color:#fff;border:none" @click="pass"
              v-if="$route.query.swcode === 'task_audit' && passDisabled && (taskName.includes(role.qualityEngineer)
                                            ||
                                            taskName.includes(role.OTAEngineer)
                                            ||
                                            taskName.includes(role.testEngineer))">
                {{ $t('pass') }}
              </auth-button >
              <auth-button :auth="todoPerms.review.pass" type="primary" :disabled="addInfoBtn" style="margin-right: 24px" @click="pass" v-else-if="$route.query.swcode === 'sw_repo_audit'">
                {{ $t('pass') }}
              </auth-button >
              <auth-button :auth="todoPerms.review.pass" type="primary" style="margin-right: 24px" @click="pass" v-else>
                {{ $t('pass') }}
              </auth-button >
              <auth-button :auth="todoPerms.review.reject" @click="reject" style="margin-right: 24px" >
                {{ $t('reject') }}
              </auth-button >
              <auth-button :auth="todoPerms.review.pass" v-if="hideAddInfoBtn || showInfo" @click="addReviewInfo" style="margin-right: 24px" >
                {{ $t('addAuditInformation') }}
              </auth-button >
            </div>
          </a-col>
        </a-row></div>
    </div>
    <a-modal v-model:visible="auditDetailViewFlag" title="查看审核详情" width="80%">
      <ApplicationGcyAuditDetailTask/>
    </a-modal>
     <a-modal :visible="visible" :title="$t('transfer')" @cancel="handleTransforCancel" @ok="handleTransfor">
          <a-form-model ref="transforForm" :rules="rules" :model="formData">
            <a-form-model-item >
               <a-row :gutter="36">
                  <a-col :md="6" :sm="24">
                    <a-form-model-item class="deepClass">
                       <span class="requiredStar">*</span>
                      {{ $t('forwardReceiver') }}
                    </a-form-model-item>
                  </a-col>
                  <a-col :md="18" :sm="24">
                    <a-form-model-item prop="transferTo">
                       <a-select
                        v-model="formData.transferTo"
                        showSearch
                        optionFilterProp="children"
                        :filterOption="$commonFun.filterOption"
                        mode="default"
                        :placeholder="$t('pleaseSelect') + $t('转交人')"
                      >
                        <a-select-option
                          v-for="item in TaskTransforArr"
                          :key="item.id"
                        >{{ item.name}}({{item.id}})</a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                </a-row>
            </a-form-model-item>
          </a-form-model>
        </a-modal>
     <!-- 新增对话框 -->
    <!-- <add-audit-info
      ref="addConfigModal"
      :formData="childFormData"
      @addOrEditDone="handleRefreshTable"
    ></add-audit-info> -->
     <!-- 撤回弹框 -->
    <a-modal
      :title="$t('systemTip')"
      :visible="isVisible"
      :closable="false"
      @ok="handleRejectOk1"
      @cancel="handleCancel1"
    >
      <p >{{$t('withdrawApplyTip')}}</p>
      <a-form-model ref="createModal" :model="model" :rules="validatorRules">
        <a-form-model-item prop="cancelReason" >
        <span slot="label" style="font-weight:bold">
          {{ $t('撤回原因') }}
        </span>
          <a-textarea v-model="model.cancelReason" placeholder="请填写撤回原因" :rows="4" allow-clear />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import ApplicationDetailTestCar from './components/ApplicationDetailTestCarCompt'
import ApplicationDetailAddCar from './components/ApplicationDetailAddCarCompt'
import ApplicationDetailTask from './components/ApplicationDetailTaskCompt'
import ApplicationDetailService from './components/ApplicationDetailServiceCompt'
import ApplicationDetailStrategy from './components/ApplicationDetailStrategyCompt'
import ApplicationDetailSoftwareMC from './components/ApplicationDetailSoftwareMCCompt'
import ApplicationGcyDetailTask from './components/ApplicationGcyDetailTaskCompt'
import ApplicationGcyAuditDetailTask from './components/ApplicationGcyAuditDetailTaskCompt'
import ReviewProcess from '@/views/todo/myApplication/components/ReviewProcessCompt'
import ReviewProcessAction from '@/views/todo/myReview/components/ReviewProcessActionCompt'
import AuthButton from '@/components/AuthButton'
import AddAuditInfo from './components/AddAuditInfo.vue'
import { todoPerms } from '@/config/permission/index'
import { minxinDrawerUse } from '@/utils/mixin'
import OTAReviewDetail from '../myReview/components/OTAReviewDetail.vue'
import QualityReviewDetail from '../myReview/components/QualityReviewDetail.vue'
import TestReviewDetail from '../myReview/components/TestReviewDetail.vue'
import myApplyApi from "@/api/modules/todo/myApply"
import {OTAEngineer,qualityEngineer,testEngineer} from "@/views/todo/myReview/config/nodeNameList.js"
import ApplicationDetailRegisterCompt from './components/ApplicationDetailRegisterCompt.vue'
import { checkTextLen } from '@/utils/validate'
export default {
  mixins: [minxinDrawerUse],
  components: {
    ApplicationDetailTask,
    ApplicationDetailAddCar,
    ApplicationDetailTestCar,
    ReviewProcess,
    AuthButton,
    ApplicationDetailService,
    ApplicationDetailStrategy,
    ReviewProcessAction,
    ApplicationDetailSoftwareMC,
    ApplicationGcyDetailTask,
    ApplicationGcyAuditDetailTask,
    ApplicationDetailRegisterCompt,
    AddAuditInfo,
    OTAReviewDetail,
    QualityReviewDetail,
    TestReviewDetail
  },
  data () {
    return {
      isVisible:false,
      model:{
        cancelReason:undefined
      },
      validatorRules:{
        cancelReason: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen(200) }],
      },
      visible:false,
      TaskTransforArr:[],
      passDisabled:false,
      BottomType: '',
      endTime: '',
      fileLimitObj: {
        fileCount: 1,
        fileSize: 1
      },
      formData:{
        transferTo:undefined
      },
      rules:{
        transferTo: [{ required: true, message: this.$t('pleaseSelect')}],
      },
   
      hideWithdrawBtn: false,
      hideAddInfoBtn: false,
      addInfoBtn: false,
      todoPerms,
      auditDetailViewFlag:false,
      taskType:'',
      childFormData: {},
      upgradeTriggerType:0,
      // 审核层级
      taskName:'',
      ReviewDetail:null,
      showInfo:false,
      role:{
        OTAEngineer,
        qualityEngineer,
        testEngineer
      }
    }
  },
  computed: {
    // 因为是公用的申请内容组件，所以根据路由参数传过来的业务code去判断应该加载何种页面，跟后端确定过业务code不会更改，只会新增，新增会同步前端进行开发
    changeCompt () {
      if (this.$route.query.swcode === 'task_audit') {
        // liang.minglong,紧急OTA去掉
        //return 'ApplicationDetailTask'
        return 'ApplicationGcyDetailTask'
      // eslint-disable-next-line no-else-return
      } else if (this.$route.query.swcode === 'strategy_audit') {
        return 'ApplicationDetailStrategy'
      } else if (this.$route.query.swcode === 'service_audit') {
        return 'ApplicationDetailService'
      } else if (this.$route.query.swcode === 'sw_repo_audit') {
        return 'ApplicationDetailSoftwareMC'
      } else if (this.$route.query.swcode === 'addcar_audit') {
        return 'ApplicationDetailAddCar'
      } else if (this.$route.query.swcode === 'gcy_task_audit') {
        return 'ApplicationGcyDetailTask'
      } else if (this.$route.query.swcode === 'testcar_audit' ||
                this.$route.query.swcode === 'testcar_audit_stop' ||
                this.$route.query.swcode === 'testcar_audit_resume' ||
                this.$route.query.swcode === 'testcar_audit_delete') {
        return 'ApplicationDetailTestCar'
      } else if (this.$route.query.swcode === 'user_register') {
        return 'ApplicationDetailRegisterCompt'
      }
      return ''
    },
  },
  methods: {
    initQuery (val) {
      if (val.aorr === 'a') {
        if (val.status === '10' || val.status === '0') {
          this.BottomType = 'pendingApplication'
        } else if (val.status === '20') {
          this.BottomType = 'passedApplication'
        } else if (val.status === '30') {
          this.BottomType = 'rejectedApplication'
        } else if (val.status === '40') {
          this.BottomType = 'canceledApplication'
        }else if (val.status === '70') {
          this.BottomType = 'upShelvesApplication'
        }else if (val.status === '80') {
          this.BottomType = 'downShelvesApplication'
        }
      } else {
        // 从我的审核页面跳转过来的
        if (val.status === '10' || val.status === '0') {
          if(val.midParam==='50'){
            this.BottomType = 'transforReview'
          }else{
            this.BottomType = 'pendingReview'
          }
        } else if (val.status === '20') {
          this.BottomType = 'passedApplication'
        } else if (val.status === '30') {
          this.BottomType = 'rejectedApplication'
        } else if (val.status === '40') {
          this.BottomType = 'canceledApplication'
        } else if(val.status === '50'){
          if(val.midParam==10){
            this.BottomType = 'pendingReview'
            return
          }
          this.BottomType = 'transforReview'
        }
      }
    },
     handleTransforCancel() {
      this.visible = false
    },
    handleTransfor() {
      this.$refs.transforForm.validate(valid=> {
        if (valid) {
          let model={
            taskComment:this.$refs.actionCompt.formData.taskComment,
            taskId:this.$route.query.p,
            transferTo:this.formData.transferTo,
            fileIds:this.$refs.actionCompt.formData.fileIds,
          }
          myApplyApi.auditTransfor(model).then(res => {
            if (res.data=='转交成功') {
              this.$message.success(res.data)
              // 跳转到我的审核界面
                   this.$store
                    .dispatch('tagsView/delView', this.$route.fullPath)
                    .then(this.$router.replace({ path: '/todo/myReview' }))
            } else {
              this.$message.warning(res.data)
            }
          })
        }
      })
    },
     // 新增或编辑配置成功以后刷新表格
    handleRefreshTable () {
      this.addInfoBtn=false
      // this.$refs.flowConfigTableComp.refreshData(true)
    },
    // 后端控制上传文件的限制
    handleFileLimit (data) {
      this.fileLimitObj = data
    },
    // 控制撤回按钮是否显示
    handleHideWithdrawBtn (bool) {
      this.hideWithdrawBtn = bool
    },
    // 控制添加补充信息按钮是否显示
    handleAddInfodrawBtn (bool) {
      this.hideAddInfoBtn = bool
    },
    addInfodrawBtn (bool) {
      this.addInfoBtn = bool
    },
    handlerShowInfoBtn(bool){
      this.showInfo=bool
    },
    // 完成时间
    handleEndTime (data) {
      this.endTime = this.$options.filters.moment(data)
    },
    // 催办
    handleUrge () {
      const vm = this
      this.$confirm({
        title: vm.$t('systemTip'),
        content: vm.$t('urgeApplyTip'),
        onOk () {
          vm.$api.urgeMyApply({ instanceId: vm.$route.query.id }).then((res) => {
            if (res.message === 'success') {
              vm.$message.success(vm.$t('5089'))
              vm.$store.dispatch('tagsView/delView', vm.$route.fullPath)
                .then(vm.$router.push({ path: '/todo/myApplication' }))
            }
          })
        },
        onCancel () { }
      })
    },
    // 撤回
    handleCancel () {
      this.isVisible=true
      this.$nextTick(() => {
          this.$refs.createModal.resetFields()
      })
      this.model.instanceId=this.$route.query.id
    },
     handleRejectOk1(){
      const vm = this
      vm.$refs.createModal.validate(valid => {
        if (valid) {
          vm.$api.cancelMyApply(this.model).then(() => {
            vm.$message.success(vm.$t('withdraw') + vm.$t('success'))
            vm.isVisible=false
            vm.$store.dispatch('tagsView/delView', vm.$route.fullPath)
            .then(vm.$router.push({ path: '/todo/myApplication' }))
          })
        }
      })
    },
    handleCancel1(){
       this.isVisible=false
    },
    // 驳回审核
    reject () {
      const vm = this
      if (this.$refs.actionCompt.formData.taskComment === ''|| this.$refs.actionCompt.formData.taskComment === undefined) {
        this.$message.warning('审批意见不能为空')
      }else {
        this.$api.rejectThisAudit(vm.$refs.actionCompt.formData).then((res) => {
          if (res.message === 'success') {
            vm.$store.dispatch('tagsView/delView', vm.$route.fullPath)
              .then(vm.$router.push({ path: '/todo/myReview' }))
          }
        })
      }
    },
    passToMyReview(){
      const vm = this
      vm.$store.dispatch('tagsView/delView', vm.$route.fullPath)
      .then(vm.$router.push({ path: '/todo/myReview' }))
    },
    // 通过审核
    pass () {
      const vm = this
      if(this.$route.query.swcode === 'user_register'){
        // console.log('@@@@@@@@@@dsaasd',this.$refs.actionCompt.formData)
        this.$api.validateOrgAndRole(this.$refs.actionCompt.formData)
        .catch(res=>{

          return
        })
      }
      if(this.passDisabled && this.$route.query.swcode === 'task_audit'){
        this.$message.warning('请补充待审核信息')
      }
      else if (this.$refs.actionCompt.formData.taskComment === '' || this.$refs.actionCompt.formData.taskComment === undefined) {
        this.$message.warning('审批意见不能为空')
      }
      else {
        if(this.taskName.includes(OTAEngineer) && this.$route.query.swcode === 'task_audit'){
          myApplyApi.uploadOTAReviewDetail(this.ReviewDetail).then(res=>{
            if (res.message === 'success') {
              this.passToMyReview()
            }
          })
        }
        else if(this.taskName.includes(testEngineer) && this.$route.query.swcode === 'task_audit'){
          myApplyApi.uploadTestReviewDetail(this.ReviewDetail).then(res=>{
            if (res.message === 'success') {
              this.passToMyReview()
            }
          })
        }
        else if(this.taskName.includes(qualityEngineer) && this.$route.query.swcode === 'task_audit'){
          myApplyApi.uploadQualityReviewDetail(this.ReviewDetail).then(res=>{
            if (res.message === 'success') {
              this.passToMyReview()
            }
          })
        }
        else{
          this.$api.passThisAudit(vm.$refs.actionCompt.formData).then((res) => {
            if (res.message === 'success') {
              this.passToMyReview()
            }
          })
        }
      }
    },
    // 这里是从我的审核列表页跳转进来会传p,从我的申请列表页跳转进来不会传p,p是taskId
    getTaskName(){
    if (this.$route.query.p) {
      this.$api.getTaskReviewDetail({
        id:this.$route.query.p
      }).then((res)=>{
        if(res.data.length>0){
          this.taskName=res.data[0].taskName
          if( this.$route.query.swcode === 'task_audit' &&
            (this.taskName.includes(qualityEngineer)
            ||
            this.taskName.includes(OTAEngineer)
            ||
            this.taskName.includes(testEngineer))){
              this.passDisabled=true
            }
        }else{
           this.$message.warning('当前节点名称不存在！')
        }
      })
    }
    },
    saveReviewInfo (data) {
      this.passDisabled=false
      this.ReviewDetail=data
      this.toggleDrawerMain(false)
    },
    saveTestInfo (data) {
      this.addInfoBtn=false
      return this.$api.addTestInfoDetail(data)
    },
    // 弹出转交弹框
    transferReviewInfo(){
       if (this.$refs.actionCompt.formData.taskComment === '' || this.$refs.actionCompt.formData.taskComment === undefined) {
        this.$message.warning('审批意见不能为空')
      }else{
        this.visible=true
        console.log(this.$route.query.p,'9987771111')
        this.$nextTick(() => {
          this.$refs.transforForm.resetFields()
        })
        myApplyApi.getTaskTransfor(this.$route.query.p).then(res=>{
            if (res.message === 'success') {
              this.TaskTransforArr=res.data
            }
          })
      }
    },
    // 补充审核信息
    async addReviewInfo(){
      if(this.$route.query.swcode === 'sw_repo_audit'){
        // this.$refs.addConfigModal.switchVisible(true, 'add', null)
        const buttons = this.getRightDrawerFooterButtons({
          method: 'saveTestInfo'
        })
        this.showRightDrawerNoReset(AddAuditInfo, this.$t('testInformation'), buttons, 'small', {
          formData:this.childFormData
        })
      }
      if(this.$route.query.swcode === 'task_audit'){
        const buttons = this.getRightDrawerFooterButtons({
          method: 'saveReviewInfo'
        })
        if(this.taskName.includes(qualityEngineer)){
          this.$api.getTaskInfor({
            id:this.$route.query.key
          }).then((response)=>{
            this.showRightDrawerNoReset( QualityReviewDetail, this.taskName, buttons, 'large', {
              upgradeTriggerType:this.upgradeTriggerType,
              auditInfo:this.$refs.actionCompt.formData,
              strategyId:response.data.strategyId,
              taskId:this.$route.query.key
            })
          })
        }else if(this.taskName.includes(OTAEngineer)){
          this.showRightDrawerNoReset(OTAReviewDetail, this.taskName, buttons, 'small', {
            auditInfo:this.$refs.actionCompt.formData
          })
        }else if(this.taskName.includes(testEngineer)){
          this.showRightDrawerNoReset(TestReviewDetail, this.taskName, buttons, 'small', {
            auditInfo:this.$refs.actionCompt.formData
          })
        }
      }
    },
    // 二次确认审核状态是否变化(从邮件过来，流程或签，审核状态可能已经变化)
    hancleStatusCheck (data) {
      if (this.$route.query.status) {
        if (this.$route.query.status * 1 !== data) {
          const query = { ...this.$route.query }
          query.status = data
          this.$router.replace({ path: this.$route.path, query })
        }
      }
    },
    // 二次确认审核状态是否变化(从邮件过来，流程或签，审核状态可能已经变化)
    hancleStatusCheck (data) {
      if (this.$route.query.status) {
        if (this.$route.query.status * 1 !== data) {
          const query = { ...this.$route.query }
          query.status = data
          this.$router.replace({ path: this.$route.path, query })
        }
      }
    },
    auditDetailView(){
      this.auditDetailViewFlag=true;
    },
    getTaskType(data) {
      this.taskType = data;
    },
    getUploadType(data){
      this.upgradeTriggerType=data
    }
  },
  created(){
    this.initQuery(this.$route.query);
    if(this.$route.query.aorr === 'r' ){
      this.getTaskName()
    }
  }
}
</script>
<style lang="less" scoped>
.taskVerifyDetail {
  display: flex;
  flex-direction: column;
  .taskVerifyDetailTop {
    position: relative;
    flex: 1;
    overflow: auto;
    padding: 15px 24px;
    min-width: 800px;
  }
  .taskVerifyDetailFooter {
    font-size: 18px;
    padding: 15px 24px;
    flex: none;
    border-top: 1px solid @borderColor;
    .ok {
      color: #46d5a2;
      font-weight: bold;
    }
    .reject {
      color: #fe8b67;
      font-weight: bold;
    }
    .marginRightText{
      margin-right: 36px;
    }
    .marginRightTextBigger{
      margin-right: 66px;
    }
    .titleBold{
      font-weight: 600;
    }
  }
}
</style>
